package com.banzhi.shop.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;

import com.banzhi.shop.R;
import com.banzhi.shop.adapter.ChoiceAddressAdapter;
import com.banzhi.shop.base.BaseActivity;
import com.banzhi.shop.entity.ChoiceAddress.ChoiceAddress_Data;
import com.banzhi.shop.model.CallBack.ChoiceAddressCallBack;
import com.banzhi.shop.model.IChoiceAddressModel;
import com.banzhi.shop.model.Impl.ChoiceAddressImpl;
import com.banzhi.shop.utils.LoadingDialogUtils;
import com.banzhi.shop.utils.NoTokenUtils;
import com.banzhi.shop.utils.ToastUtils;
import com.banzhi.shop.utils.Translucent;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 选址地址列表页面
 */
public class ChoiceAddressActivity extends BaseActivity implements View.OnClickListener, ChoiceAddressCallBack, SwipeRefreshLayout.OnRefreshListener {
    /**
     * 退出
     */
    private ImageView ivback;
    /**
     * 添加地址
     */
    private RelativeLayout rladd_address;
    private ListView listview;
    private SwipeRefreshLayout srllistview;
    private IChoiceAddressModel model;
    private List<ChoiceAddress_Data> data = new ArrayList<>();
    private ChoiceAddressAdapter addressAdapter;
    private RelativeLayout rlnodata;
    private boolean isresult;
    /**
     * 传过来的id  用于更新数据集合的数据
     */
    private int position;
    private int page = 1;
    /**
     * 判断listview是不是滑到最低端了
     */
    private boolean isbottom;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_choice_address);
        Translucent.setTranslucent(this);
        Intent intent = getIntent();
        isresult = intent.getBooleanExtra("isresult", false);
        setinits();
        setListeners();
        model = new ChoiceAddressImpl();
        LoadingDialogUtils.showProgress(this, "正在加载,请稍后~");
        model.getData(page, this);
    }

    @Override
    protected void onStart() {
        super.onStart();
        model.getData(page, this);
    }

    private void setinits() {
        ivback = (ImageView) findViewById(R.id.iv_back);
        rladd_address = (RelativeLayout) findViewById(R.id.rl_add_address);
        listview = (ListView) findViewById(R.id.listview);
        srllistview = (SwipeRefreshLayout) findViewById(R.id.srl_listview);
        srllistview.setColorSchemeResources(R.color.themeColor);
        srllistview.setProgressBackgroundColorSchemeResource(R.color.colorWhite);
        rlnodata = (RelativeLayout) findViewById(R.id.rl_nodata);

    }

    private void setListeners() {
        srllistview.setOnRefreshListener(this);
        ivback.setOnClickListener(this);
        rladd_address.setOnClickListener(this);
        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (isresult) {
                    Intent intent = new Intent();
                    intent.putExtra("id", data.get(position).getId());
                    intent.putExtra("address", data.get(position).getProvince() + data.get(position).getCity() + data.get(position).getArea() + data.get(position).getAddress());
                    setResult(1, intent);
                    finish();
                }
            }
        });
        listview.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE && isbottom) {
                    page++;
                    LoadingDialogUtils.showProgress(ChoiceAddressActivity.this, "正在加载,请稍后~");
                    model.getData(page, ChoiceAddressActivity.this);
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                if ((firstVisibleItem + visibleItemCount) == totalItemCount) {
                    isbottom = true;
                } else {
                    isbottom = false;
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.rl_add_address:
                Intent intent = new Intent(this, AddAddressActivity.class);
                startActivity(intent);
                break;
        }
    }

    /**
     * @param object 获取地址列表成功
     */
    @Override
    public void ongetDataSuccess(Object object) {
        if (srllistview.isRefreshing()) {
            srllistview.setRefreshing(false);
        }
        LoadingDialogUtils.dismiss();
        if (page == 1) {
            data.clear();
        } else {
            if (((List<ChoiceAddress_Data>) object).size() == 0) {
//                ToastUtils.makeToastShort("没有更多了");
                return;
            }
        }
        data.addAll((List<ChoiceAddress_Data>) object);

        if (data.size() == 0) {
            rlnodata.setVisibility(View.VISIBLE);
        } else {
            rlnodata.setVisibility(View.GONE);
        }

        if (addressAdapter == null) {
            addressAdapter = new ChoiceAddressAdapter(this, data);
            listview.setAdapter(addressAdapter);
        } else {
            addressAdapter.notifyDataSetChanged();
        }
        addressAdapter.setCallBack(new ChoiceAddressAdapter.setDefaultAddressCallBack() {
            @Override
            public void setDefaultAddress(String id, int position) {
                LoadingDialogUtils.showProgress(ChoiceAddressActivity.this, "正在加载,请稍后~");
                model.ChangeDefaultAddress(id, ChoiceAddressActivity.this);
                ChoiceAddressActivity.this.position = position;
            }

            @Override
            public void deleteAddress(String id, int position) {
                LoadingDialogUtils.showProgress(ChoiceAddressActivity.this, "正在加载,请稍后~");
                model.deleteAddress(id, "2", ChoiceAddressActivity.this);
                ChoiceAddressActivity.this.position = position;
            }
        });
    }

    /**
     * @param object 获取地址列表失败
     */
    @Override
    public void ongetDataError(Object object) {
        if (srllistview.isRefreshing()) {
            srllistview.setRefreshing(false);
        }
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }

    /**
     * @param object 修改默认地址成功
     */
    @Override
    public void ChangeDefaultAddressSuccess(Object object) {
        LoadingDialogUtils.dismiss();
        listview.setSelectionFromTop(position, 0);
        for (int i = 0; i < data.size(); i++) {
            data.get(i).setIsdefault("0");
        }
        data.get(position).setIsdefault("1");
        addressAdapter.notifyDataSetChanged();
    }

    /**
     * @param object 修改默认地址失败
     */
    @Override
    public void ChangeDefaultAddressError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }

    /**
     * @param object 删除地址成功
     */
    @Override
    public void deleteAddressSuccess(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
        data.remove(position);
        addressAdapter.notifyDataSetChanged();
        if (data.size() == 0) {
            rlnodata.setVisibility(View.VISIBLE);
        } else {
            rlnodata.setVisibility(View.GONE);
        }

    }

    /**
     * @param object 删除地址失败
     */
    @Override
    public void deleteAddressError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }

    @Override
    public void onRefresh() {
        LoadingDialogUtils.showProgress(ChoiceAddressActivity.this, "正在加载,请稍后~");
        page = 1;
        model.getData(page, this);
    }
}
